import MarkdownIt from 'markdown-it';
import createDOMPurify from 'dompurify';

const URL_WHITELIST = /^(?:https?:\/\/)/i;
const SANITIZE_OPTIONS = {
  ALLOWED_URI_REGEXP: URL_WHITELIST,
  ADD_ATTR: ['target', 'rel']
};

const markdownIt = new MarkdownIt({
  html: false,
  linkify: true,
  typographer: true,
  breaks: true
});

const defaultLinkRenderer = markdownIt.renderer.rules.link_open
  || ((tokens, idx, options, env, self) => self.renderToken(tokens, idx, options));

markdownIt.renderer.rules.link_open = (tokens, idx, options, env, self) => {
  const token = tokens[idx];
  const hrefIndex = token.attrIndex('href');

  if (hrefIndex >= 0) {
    const href = token.attrs[hrefIndex][1].trim();
    if (URL_WHITELIST.test(href)) {
      token.attrs[hrefIndex][1] = href;
      token.attrSet('target', '_blank');
      token.attrSet('rel', 'noopener noreferrer');
    } else {
      token.attrs.splice(hrefIndex, 1);
    }
  }

  return defaultLinkRenderer(tokens, idx, options, env, self);
};

let purifier;

function sanitize(html) {
  if (!purifier && typeof window !== 'undefined' && window.document) {
    purifier = createDOMPurify(window);
  }

  if (purifier) {
    return purifier.sanitize(html, SANITIZE_OPTIONS);
  }

  return html;
}

export function renderMarkdown(markdown = '') {
  if (!markdown) {
    return '';
  }

  const rendered = markdownIt.render(markdown);
  return sanitize(rendered);
}
